package admin

import (
	"context"
	"github.com/gin-gonic/gin"
	"wzgames/internal/admin/adsv"
	"wzgames/internal/admin/api"
	"wzgames/internal/app"
	"wzgames/internal/client"
	"wzgames/internal/codec/sfs"
	"wzgames/internal/gloader"
	"wzgames/internal/response"
	"wzgames/pkg/actor/actorservice"
	"wzgames/pkg/server/http"
	"wzgames/pkg/server/http/middleware"
	"wzgames/pkg/server/ws"
)

func RunServer() error {
	bootc := gloader.BootConfig()
	return app.Start(bootc,
		app.BeforeStart(func(ctx context.Context) error {
			err := gloader.CommMgr().LoadSysConfig()
			if err == nil {
				err = gloader.CommMgr().LoadSysCurrencies(true)
			}
			if err != nil {
				return err
			}
			return gloader.CommMgr().WatchCommConfig()
		}, func(ctx context.Context) error {
			err := gloader.CommMgr().InitWdb()
			if err == nil {
				err = gloader.CommMgr().InitRedis()
			}
			if err == nil {
				err = gloader.CommMgr().InitNats()
			}
			if err != nil {
				return err
			}
			response.InitRawPacketPool()
			adsv.InitSV()
			return actorservice.StartService(Actor())
		}),
		app.Server(
			http.NewHttpServer(bootc.Node().HttpConf,
				http.Use(middleware.Logger(), middleware.Gate(), middleware.Recovery(), middleware.Options(), middleware.Secure()),
				http.Route(func(g *gin.Engine) {
					api.InitRoute(g)
				}),
			),
			ws.NewWebSocketServer(bootc.Node().WsConf,
				ws.Transmitter(sfs.NewWSMessageTransmitter(sfs.NewDefaultSFSDataSerializer())),
				ws.SendCallback(response.ReleaseRawPacket),
				ws.ActorAttach(Actor()),
			),
		),
		app.AfterStop(func(ctx context.Context) error {
			Actor().OnDestroy()
			client.CloseUCClient()
			client.CloseCatClient()
			gloader.Res().Stop()
			return nil
		}),
	)
}
